package com.thinkgem.jeesite.common.weixin;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WxTest {
    // 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https
    HttpClient client = new HttpClient();
    Gson g=new Gson();
    String appSecret="ce9689a6d6596b54b9cff950f1f86427";

    String appId="wxe6863d160c0f4ec4";

    /**
     * 测试模板和用户Id
     */
    String  pushOpenId="oJIXH1aEgc_cBDCVc7xigslAy0Ak";
    String templeID="1RYINlG7R6KlPwO-N-c4d3fwTVsjzSaAdrf3T25cNxk";
    /**
     * 获取微信的Access_token
     * @return
     */
    private String getAccess_token(){
        HttpMethod getmethod=new GetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret);
        Map<String,Object> map=null;
        try {
            client.executeMethod(getmethod);
            System.out.println("---->"+getmethod.getStatusLine());
            map = new Gson().fromJson(getmethod.getResponseBodyAsString(), new TypeToken<HashMap<String,Object>>(){}.getType());
            return (String)map.get("access_token");
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }finally {
            getmethod.releaseConnection();
        }
    }

    /**
     * 打印公众号模板
     */
    private void getTemplate(){
        HttpMethod getTemplate=new GetMethod("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+getAccess_token());
        try {
            client.executeMethod(getTemplate);
            System.out.println("---->"+getTemplate.getStatusLine());
            //打印返回的信息
            System.out.println(getTemplate.getResponseBodyAsString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            getTemplate.releaseConnection();
        }
    }

    /**
     * 获取关注者微信关注者信息,存在指定路径
     */
    private void getUserInfos(String filePath){
        HttpMethod getUser=new GetMethod("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+getAccess_token()+"&next_openid=");
        Map<String,Object> datamap=null;
        try{
            client.executeMethod(getUser);
            System.out.println(new Date()+":获取用户信息OpenID---->"+getUser.getStatusLine());
            datamap = new Gson().fromJson(getUser.getResponseBodyAsString(), new TypeToken<HashMap<String,Object>>(){}.getType());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            getUser.releaseConnection();
        }
        //打印返回的信息
        LinkedTreeMap<String,Object> t=(LinkedTreeMap)datamap.get("data");
        ArrayList<String> list=(ArrayList<String>)t.get("openid");

        HttpMethod getUserInf=null;
        filePath=filePath==null?"C:/Users/Administrator/Desktop/userList.txt":filePath;
        File file=new File(filePath);
        if(!file.exists()) try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileWriter  fw=null;
        try{
             if(file.exists())file.createNewFile();
            fw=new FileWriter(filePath,true);
            StringBuilder sb =new StringBuilder();
            for(String openid: list){
                getUserInf=new GetMethod("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+getAccess_token()+"&openid="+openid+"&lang=zh_CN");
                client.executeMethod(getUserInf);
                byte[] content = getUserInf.getResponseBodyAsString().getBytes("ISO8859-1");
                fw.write(new String(content, "utf-8")+"\r\n");
                getUserInf.releaseConnection();
                fw.flush();
            }
            getUser.releaseConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 确认用户同意授权
     */
    public void UserConfirm(){
        HttpMethod comfim=new GetMethod("https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid="+appId+"&scene=1000" +
                "&template_id="+templeID+"&redirect_url=http%3a%2f%2fsupport.qq.com&reserved=test#wechat_redirect");
        try {
            client.executeMethod(comfim);
            System.out.println("---->"+comfim.getStatusLine());
            //打印返回的信息
            System.out.println(comfim.getResponseBodyAsString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            comfim.releaseConnection();
        }
    }

    /**
     * 通过模板推送消息
     */
    public void pushMessageByTemplate(){
        Map datamap=new HashMap();
        Map first=new HashMap();
        Map keyword1=new HashMap();
        Map keyword2=new HashMap();
        Map keyword3=new HashMap();
        Map remark=new HashMap();
        Map dataMap=new HashMap();

        first.put("value","康力，您好！");
        keyword1.put("value","您有三条待办事项（请假未处理！）");
        keyword2.put("value","分别为1,2,3三位同学！");
        keyword3.put("value","2017-11-23");
        remark.put("value","点此进行处理！");

        datamap.put("first",first);
        datamap.put("keyword1",keyword1);
        datamap.put("keyword2",keyword2);
        datamap.put("keyword3",keyword3);
        datamap.put("remark",remark);

        dataMap.put("touser",pushOpenId);
        dataMap.put("template_id", templeID);
        dataMap.put("url", "http://weixin.qq.com/download");
        dataMap.put("data", datamap);

        String s= HttpUtils.doPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getAccess_token(),dataMap);
        System.out.println(s);
    }


    /**
     * 添加客服
     */
    public void kfaccountAdd(){
        String url="https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" +getAccess_token();
        Map dataMap=new HashMap();
        dataMap.put("kf_account", "zhifang950626");
        dataMap.put("nickname", "锐取医教");
        dataMap.put("password", "rmn940904");

        String s=HttpUtils.doPost(url,dataMap);
        System.out.println(s);
    }


    public void batchget_material   (){
        String url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" +getAccess_token();
        Map dataMap=new HashMap();
        dataMap.put("type", "image");
        dataMap.put("offset", "0");
        dataMap.put("count", "20");

        String s= HttpUtils.doPost(url,dataMap);
        System.out.println(s);
    }

    public static void main(String args[]) throws IOException, InterruptedException {
        WxTest wt=new WxTest();
        wt.pushMessageByTemplate();
    }
}
